package com.example.securitymy.service.impl;

import com.example.securitymy.domain.LoginUser;
import com.example.securitymy.domain.ResponseResult;
import com.example.securitymy.domain.User;
import com.example.securitymy.service.LoginService;
import com.example.securitymy.utils.JwtUtil;
import com.example.securitymy.utils.RedisCache;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    AuthenticationManager authenticationManager;
    @Resource
    RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        String userName = user.getUserName();
        // UsernamePasswordAuthenticationToken是Authentication的实现类,封装Authentication对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticated = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) authenticated.getPrincipal();
        String userID = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userID);
        redisCache.setCacheObject("login:"+userID,loginUser);
        Map<Object,Object> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,"登录成功",map);
    }
    //登出功能
    public ResponseResult logout(){
       Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       LoginUser loginUser = (LoginUser) authentication.getPrincipal();
       Long userID = loginUser.getUser().getId();
       //删除redis中的用户信息
       redisCache.deleteObject("login:"+userID);
       return new ResponseResult<>(200,"退出成功");
    }
}
